package com.wang.friend.manager;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wang.friend.domain.user.User;
import com.wang.friend.domain.user.vo.UserVO;
import com.wang.friend.mapper.user.UserMapper;
import com.wang.common.core.constants.CacheConstants;
import com.wang.common.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class UserCacheManager {
    @Autowired
    private RedisService redisService;

    @Autowired
    private UserMapper userMapper;

    public UserVO getUserById(Long userId){
        //拼接当前用户详细信息在缓存中的key
        String userCacheKey = getUserCacheKey(userId);
        //从缓存中获取到当前用户的详细信息
        UserVO userVO =  redisService.getCacheObject(userCacheKey,UserVO.class);
        //获取到的信息不为空,延长当前key的过期并返回
        if (userVO != null){
            redisService.expire(userCacheKey,CacheConstants.USER_EXP, TimeUnit.MINUTES);
            return userVO;
        }
        //为空,从数据库中查询数据,并更新缓存
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .select(User::getUserId,
                        User::getNickName,
                        User::getHeadImage,
                        User::getSex,
                        User::getEmail,
                        User::getPhone,
                        User::getWechat,
                        User::getIntroduce,
                        User::getSchoolName,
                        User::getMajorName,
                        User::getStatus)
                .eq(User::getUserId, userId));
        //如果数据库中没有查出来,那么就直接返回null
        //todo
        //缓存穿透
        if (user == null) return null;
        //数据库中查询成功.刷新缓存
        refreshUser(user);
        userVO = new UserVO();
        //拷贝属性
        BeanUtil.copyProperties(user,userVO);
        return userVO;
    }

    private String getUserCacheKey(Long userId) {
        return CacheConstants.USER_DETAIL + userId;
    }

    /**
     * 更新缓存
     * @param user 传入的用户
     */
    public void refreshUser(User user){
        String userCacheKey = getUserCacheKey(user.getUserId());
        //更新缓存中的用户数据
        redisService.setCacheObject(userCacheKey,user);
        //刷新过期时间
        redisService.expire(userCacheKey,CacheConstants.USER_EXP, TimeUnit.MINUTES);
    }
}
